#include "graymorphology.h"
#include "funduspreprocessing.h"
using namespace std;
using namespace pip;

int main(int argc, char *argv[]){
  string program = argv[0];
  vector<string> args(argv, argv+argc);
  if (argc<2) error(program, "\nUsage: graymorphology filename -operator c -kernelrad r\n"
		    "Performs gray-scale morphology on grayscale image.\n"
		    "  c = 'o': opening\n"
		    "      'c': closing\n"
		    "      'e': erode\n"
		    "      'd': dilate\n"
		    "  using a disc kernel of radius r.\n");

  //get filename, color and medianwidth from command line
  string filename = argv[1];
  char oper = 'o';
  getScalarArg(args, "-operator", oper);
  if(oper != 'o' &&
     oper != 'c' &&
     oper != 'd' &&
     oper != 'e'){
    error(program, "Not a valid operator; use 'o', 'c', 'd', or 'e'\n");
    return 1;
  }
  int kernelrad = 1;
  getScalarArg(args, "-kernelrad", kernelrad);
  if(kernelrad<1){
    error(program, "Not a valid kernelradius; use an integer>0\n");
    return 1;
  }

  pip::Image<float> imIn;
  pip::Image<float> imOut;
  if (!importFile(imIn,filename))
    error(program, "Error reading input file (must be 2D grays-cale pip image)\n");

  // build disc shaped structure element
  pip::Image<unsigned char> se;
  discStructureElement(se, kernelrad);

  switch(oper){
  case 'o':
    grayOpening(imIn,imOut,se);
    break;
  case 'c':
    grayClosing(imIn,imOut,se);
    break;
  case 'd':
    grayDilate(imIn,imOut,se);
    break;
  case 'e':
    grayErode(imIn,imOut,se);
    break;
  }

  // Print min/max/average
  float min, max, avr;
  getMinMaxAvrImage<float>(imOut,min, max, avr);
  cout << "After morphologic operation " << oper << " : " << endl;
  cout << "min : "<<min<<", max : "<<max<<", average : "<<avr<<endl;

  // save the result image
  exportFile(imOut,"fundus_morph.pip");

  return 0;
}
